package cn.edu.hizee.gps.dao;

import cn.edu.hizee.gps.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author ZX
 */
public interface UserRepository extends JpaRepository<User,Integer>, CrudRepository<User,Integer> {

    /**
     * 用户登陆
     * @param phone
     * @param password
     * @return
     */
    User findByPhoneAndPassword(String phone, String password);

    @Override
    List<User> findAll();


    @Query(nativeQuery = true, value = "SELECT " +
            "*  " +
            "FROM " +
            "t_user " +
            "LIMIT :pageNum, :pageAmount")
    List<User> findPages(int pageNum, int pageAmount);


    /**
     * 更新用户安全信息
     * @param userId
     */
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(nativeQuery = true, value = "UPDATE t_user set t_user.is_safe = 0 WHERE t_user.id = :userId")
    Integer updateIsSafe(@Param("userId") Integer userId);

    /**
     *  查找用户信息
     * @param userId
     * @return
     */
    @Query(nativeQuery = true, value = "SELECT " +
            "t_user.id, " +
            "t_user.password, " +
            "t_user.phone, " +
            "t_user.time, " +
            "t_user.nickname, " +
            "t_user.is_safe, " +
            "t_user_info.sex " +
            "FROM " +
            "t_user " +
            "JOIN t_user_info on t_user_info.user_id = t_user.id " +
            "JOIN t_contact on t_contact.user_id = :userId " +
            "JOIN t_user_contact on t_user_contact.contact_id = t_contact.id AND t_user_contact.user_id = t_user.id ")
    List<Map> findUserList(@Param("userId") int userId);

    /**
     * 查找指定Id
     * @param userId
     * @return
     */
    List<User> findAllById(Integer userId);


    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(nativeQuery = true,value = "UPDATE t_user SET t_user.nickname = :realname, t_user.real_name = :nickname WHERE t_user.id = :userId")
    Integer updateByNickNameAndRealName(@Param("realname") String realname, @Param("nickname")String nickname, @Param("userId") Integer userId);

    /**
     * 获取id
     * @return
     */
    @Query(nativeQuery = true, value = "SELECT " +
            "t_user.id " +
            "FROM " +
            "t_user")
    List<HashMap<String, Object>> findAllId();

    User findAllByRealName(String name);
}
